<template>
  <div class="search-form-bar">
    <Form label-colon :label-width="labelWidth">
      <Row :gutter="16">
        <template v-for="item in formatList">
          <Col v-if="!item.hide" v-bind="layout" :key="`search-bar-${item.name}`">
            <FormItem :label="item.label">
              <component
                :is="componentMeta[item.type]"
                v-model="values[item.name]"
                :prop="item.name"
                v-bind="item.props || {}"
                v-on="item.listeners || null"
              />
            </FormItem>
          </Col>
        </template>
        <Col v-bind="actionSpan">
          <FormItem class="search-form-bar__action">
            <Button type="primary" @click="onSearch">查询</Button>
            <Button @click="onReset">重置</Button>
            <slot name="extra"></slot>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <Spin fix v-if="loading" />
  </div>
</template>

<script>
import { min, max } from 'lodash';
import SearchSelect from './Select';
export default {
  name: 'SearchFormBar',
  components: {
    SearchSelect
  },
  props: {
    list: {
      type: Array,
      default: () => []
    },
    showSearchButton: {
      type: Boolean,
      default: true
    },
    showResetButton: {
      type: Boolean,
      default: true
    },
    searchButtonText: {
      type: String,
      default: '查询'
    },
    resetButtonText: {
      type: String,
      default: '重置'
    },
    layout: {
      type: Object,
      default: () => {
        return {
          // <576px
          xs: 24,
          // ≥576px
          sm: 24,
          // ≥768px
          md: 12,
          // ≥992px
          lg: 8,
          // ≥1200px
          xl: 6,
          // ≥1600px
          xxl: 6
        };
      }
    },
    pagination: {
      type: [Object, Boolean],
      default: () => {
        return {
          currentPage: 1,
          pageSize: 10
        };
      }
    }
    /* defaultValue: {
      type: Object,
      default: () => {}
    } */
  },
  data() {
    return {
      componentMeta: {
        input: 'Input',
        select: 'SearchSelect',
        radio: 'Radio',
        date: 'DatePicker',
        range: 'DatePicker'
      },
      values: {}, // 参数
      initValues: {}, // 空参数

      firstInited: false,
      initLoading: false,
      labelWidth: 140
    };
  },
  watch: {
    list: {
      handler: 'setInitValue',
      immediate: true,
      deep: true
    }
  },
  computed: {
    formatList() {
      return this.list.map(item => {
        if (item.type === 'range' && !item.props.type) {
          item.props.type = 'daterange';
        }
        return item;
      });
    },
    loading() {
      return this.initLoading;
    },
    actionSpan() {
      const { layout, getActionOffset } = this;
      const spanConfig = Object.keys(layout).map(key => {
        const span = {
          [key]: {
            span: layout[key],
            offset: getActionOffset(layout[key])
          }
        };
        return span;
      });
      return spanConfig;
    }
  },
  methods: {
    setLabelWidth() {
      if (!(this.list && this.list.length)) return

      this.initLoading = true;
      const lableLengthList = this.list.map(item => {
        return item.label && typeof item.label === 'string'
          ? item.label.length
          : 0;
      });

      const maxLength = max(lableLengthList);
      const labelDom = document.getElementsByClassName(
        'ivu-form-item-label'
      )[0];
      if (labelDom) {
        let style = window.getComputedStyle(labelDom, null);
        // 冒号预留10 label左右padding
        const padding =
          10 + parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
        if (style.fontSize) {
          this.labelWidth = min([
            parseFloat(style.fontSize) * maxLength + padding,
            140
          ]);
        }
      }
      this.initLoading = false;
    },
    getActionOffset(span) {
      const totalSpan = this.list.length * span;
      return 24 - span - (totalSpan % 24);
    },
    // 初始化参数
    setInitValue() {
      // 动态计算label宽度
      this.setLabelWidth()

      const valueList = {};
      this.list.forEach(item => {
        if (item.name.indexOf('.') !== -1) {
          const [name, child] = item.name.split('.');
          valueList[name] = valueList[name] ? valueList[name] : {};
          valueList[name][child] = item.value;
        } else {
          valueList[item.name] = item.value;
        }
      });
      this.values = valueList;
      this.initValues =
        this.pagination === false
          ? { ...valueList }
          : { ...valueList, ...this.pagination };
      if (!this.firstInited) {
        this.firstInited = true;
        this.$emit('valueInited', this.values);
      }
    },
    // 查询
    onSearch() {
      this.$emit('search', this.values);
    },
    // 重置
    onReset() {
      this.values = { ...this.initValues };
      this.$nextTick(() => {
        this.$emit('search', this.values);
        let path = this.$route.path; //先获取路由路径
        this.$router.push(path)
      });
    },
    // 获取查询参数
    getSearchParams(){
      return this.values
    },
  }
};
</script>

<style lang="less">
.search-form-bar {
  &__action {
    text-align: right;
    .ivu-form-item-content {
      margin-left: 0 !important;
    }
    .ivu-btn:not(:first-of-type) {
      margin-left: 5px;
    }
  }
  position: relative;
  .ivu-date-picker {
    width: 100%;
  }

}
</style>
